const {
  collectTopicError,
  deleteCollectTopicError,
  getCollectTopicsError,
} = require("../constant/err.type");
const {
  createCollect,
  deleteUserCollect,
  getAllCollectId,
  getTopic,
} = require("../service/collect.service");

const { getComments } = require("../service/topic.service");
class CollectController {
  async collectTopic(ctx) {
    //! 直接调用service的createGoods方法
    try {
      console.log(ctx.request.body);
      const res = await createCollect(ctx.request.body);
      ctx.body = {
        code: 0,
        isCollected: true,
        message: "收藏帖子成功",
        result: res,
      };
    } catch (err) {
      console.log(err);
      return ctx.app.emit("error", collectTopicError, ctx);
    }
  }

  async deleteCollect(ctx) {
    try {
      console.log(ctx.request.body);
      const res = await deleteUserCollect(ctx.request.body);
      ctx.body = {
        code: 0,
        message: "该用户取消收藏帖子成功",
        result: res,
      };
    } catch (err) {
      console.log(err);
      return ctx.app.emit("error", deleteCollectTopicError, ctx);
    }
  }

  async getAllCollects(ctx) {
    try {
      const collect_id_arr = await getAllCollectId(ctx.request.body);
      if (collect_id_arr.length <= 0) {
        ctx.body = {
          code: 0,
          message: "该用户收藏的帖子数量为0",
          result: [],
        };
      }
      let topicArr = [];

      for (let i = 0; i < collect_id_arr.length; i++) {
        const topic_content = await getTopic(collect_id_arr[i]);
        topicArr[i] = {};
        topicArr[i].topic = topic_content;
        topicArr[i].comment_mes = [];
        const comment_mes = await getComments(collect_id_arr[i]);
        if (comment_mes.length > 0) {
          for (let j = 0; j < comment_mes.length; j++) {
            topicArr[i].comment_mes[j] = comment_mes[j].dataValues;
          }
        }
      }
      ctx.body = {
        code: 0,
        message: "获取该用户收藏的帖子详情成功",
        result: topicArr,
      };
    } catch (err) {
      console.log(err);
      return ctx.app.emit("error", getCollectTopicsError, ctx);
    }
  }
}

module.exports = new CollectController();
